package com.tianji.promotion.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.tianji.promotion.utils.CodeUtil;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.contans.RedisContans.EXANGE_CODE_SERIAL;
import static com.tianji.promotion.contans.RedisContans.UPDATE_COUPON_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author wxh
 * @since 2024-09-01
 */
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private final BoundValueOperations<String, String> serialOps;
    private final StringRedisTemplate redisTemplate;

    public ExchangeCodeServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.serialOps = redisTemplate.boundValueOps(EXANGE_CODE_SERIAL);

    }

    /**
     * 生成兑换码
     *
     * @param coupon
     */
    @Async("generateExchangeCodeExecutor")
    @Override
    @Transactional
    public void exchangeCode(Coupon coupon) {
        //1.获取需要生成的最大兑换码数量
        Integer totalNum = coupon.getTotalNum();
        //2.获取redis自增id---它是直接自增到最大的id，然后获取最大id，后面通过循环的++操作为每一个兑换码赋值id
        Long result = serialOps.increment(totalNum);//获取到了最大的序列号 需要转换类型所以在后面转为了maxSerial
        //2.1如果从redis中拿到的自增id为null的话，直接结束
        try {
            if (ObjectUtil.isEmpty(result)) {
                return;
            }
            //最大的序列号
            int maxSerial = result.intValue();
            //3.创建一个集合来存储兑换码的数据
            List<ExchangeCode> codeList = new ArrayList<>();
            for (int serial = maxSerial - totalNum + 1; serial <= maxSerial; serial++) {
                //3.1.生成兑换码
                String exangeCode = CodeUtil.generateCode(serial, coupon.getId());
                //3.2分装数据（兑换码、兑换码的id、兑换码过期时间、兑换码属于哪个优惠券的）,添加至codeList和集合中
                codeList.add(new ExchangeCode().setCode(exangeCode)
                        .setId(serial)
                        .setExpiredTime(coupon.getIssueEndTime())
                        .setExchangeTargetId(coupon.getId()));
            }
            //4.批量插入到兑换码表中
            saveBatch(codeList);
        } catch (Exception e) {
            //5.如果获取的自增序列号不为空，但是生成兑换码循环出错了，可以回滚到刚开始的序列号
            if (ObjectUtil.isNotEmpty(result)) {
                serialOps.decrement(totalNum);
            }
            e.printStackTrace();
            throw new BizIllegalException("");
        }
    }

    /**
     * 修改兑换码的状态
     *
     * @param serialNum
     * @param mark      用来标记是否被兑换过
     */
    @Override
    public boolean UpdateExchangeStyatus(long serialNum, boolean mark) {
        //1.使用bitmap命令兑换
        Boolean isTrue = redisTemplate.opsForValue().setBit(UPDATE_COUPON_KEY, serialNum, mark);
        //2.返回结果
        return ObjectUtil.isNotEmpty(isTrue) && isTrue;
    }
}
